﻿using SIG.Model;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using SIG.Service;
using SIG.Model.Enums;
using System.Threading.Tasks;
using SIG.ViewModel;
using SIG.Model.Identity;
using AutoMapper;
using SIG.Infrastructure.Configs;
using SIG.WebMVC.Filters;
using SIG.ViewModel.Admin.Menu;
using SIG.Resources.Admin;
using SIG.ViewModel.Admin.Menus;
using SIG.InputModel.Admin.Menus;
using System;

namespace SIG.WebMVC.Areas.Admin.Controllers
{
    //  [Authorize(Roles = "创始人")]
    [SIGAuth]
    public class MenuController : BaseController
    {
        private readonly ICategoryService _categoryService;   
        private readonly IMenuService _menuService;
        private readonly IMapper _mapper;

        public MenuController(IMenuService menuService, ICategoryService categoryService, IMapper mapper)
        {
            _menuService = menuService;
            _categoryService = categoryService;
            _mapper = mapper;

        }
        //
        // GET: /Admin/Menu/ 
        public ActionResult Index()
        {
            IEnumerable<Category> menuCategories = _categoryService.GetAllCategories(ModelType.MENU);   
            if (!User.IsInRole("创始人"))
            {
                menuCategories = menuCategories.Where(c => c.Id != SettingsManager.Menu.BackMenuCId);
                return View(menuCategories);
            }         
            return View(menuCategories);
        }

        /// <summary>
        /// 获取单组菜单
        /// </summary>
        /// <param name="categoryId"></param>
        /// <returns></returns>
        [AllowAnonymous]
        public async Task<ActionResult> GetMenus(int categoryId)
        {
            var menus = await _menuService.GetMenus(categoryId);
            return PartialView("_MenuList",menus);
        }

        [AllowAnonymous]
        public ActionResult LeftNavs(int categoryId)
        {
            //var menus = _menuService.GetFaltMenus(categoryId);
            var menus = _menuService.GetShowMenus(categoryId);
            LeftNavVM vm = new LeftNavVM
            {
                Menus = _mapper.Map<IEnumerable<Menu>, IEnumerable<BaseMenuVM>>(menus),
                CurrentMenu = _menuService.GetCurrenMenu()
            };

            return PartialView("_LeftNav", vm);
        }


        /// <summary>
        /// 面包屑
        /// </summary>
        [AllowAnonymous]
        public ActionResult Crumbs(string areaName,string controller,string action)
        {            

            return PartialView("_Crumbs", _menuService.CurrenMenuCrumbs(SettingsManager.Menu.BackMenuCId));
        }

        [HttpGet]     
        public ActionResult CreateMenu(int categoryId, int parentId)
        {
            Menu vMenu = new Menu(); 
            MenuIM newDto = _mapper.Map<MenuIM>(vMenu);
        
            newDto.CategoryId = (int)categoryId;          
            newDto.ParentId = parentId;
            return PartialView("_MenuCreate", newDto);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<JsonResult> CreateMenu(MenuIM menu)
        {

            if (ModelState.IsValid)
            {
                Menu vMenu = _mapper.Map<Menu>(menu);
                var parentMenu = _menuService.GetById(vMenu.ParentId);
                vMenu.LayoutLevel = parentMenu.LayoutLevel + 1;
               
                //自动添加通用操作
                if (vMenu.CategoryId == SettingsManager.Menu.BackMenuCId && vMenu.MenuType == Model.Enum.MenuType.PAGE)
                {
                    vMenu.ChildMenus.Add(new Menu
                    {
                        Title = "添加",
                        Controller = vMenu.Controller,
                        Action = "Add",
                        Area = vMenu.Area,
                        MenuType = Model.Enum.MenuType.ACTION,
                        CategoryId = vMenu.CategoryId,
                        LayoutLevel = vMenu.LayoutLevel + 1
                    });
                    vMenu.ChildMenus.Add(new Menu
                    {
                        Title = "编辑",
                        Controller = vMenu.Controller,
                        Action = "Edit",
                        Area = vMenu.Area,
                        MenuType = Model.Enum.MenuType.ACTION,
                        CategoryId = vMenu.CategoryId,
                        LayoutLevel = vMenu.LayoutLevel + 1
                    });
                    vMenu.ChildMenus.Add(new Menu
                    {
                        Title = "显示/隐藏",
                        Controller = vMenu.Controller,
                        Action = "IsActive",
                        Area = vMenu.Area,
                        MenuType = Model.Enum.MenuType.ACTION,
                        CategoryId = vMenu.CategoryId,
                        LayoutLevel = vMenu.LayoutLevel + 1
                    });
                    vMenu.ChildMenus.Add(new Menu
                    {
                        Title = "删除",
                        Controller = vMenu.Controller,
                        Action = "Delete",
                        Area = vMenu.Area,
                        MenuType = Model.Enum.MenuType.ACTION,
                         CategoryId = vMenu.CategoryId,
                        LayoutLevel = vMenu.LayoutLevel + 1
                    });
                    vMenu.ChildMenus.Add(new Menu
                    {
                        Title = "分类设置",
                        Controller = vMenu.Controller,
                        Action = "PageSizeSet",
                        Area = vMenu.Area,
                        MenuType = Model.Enum.MenuType.ACTION,
                        CategoryId = vMenu.CategoryId,
                        LayoutLevel = vMenu.LayoutLevel + 1
                    });
                }

                _menuService.CreateAndSort(vMenu);

             

                var menus = await _menuService.GetMenus(vMenu.CategoryId);
                AR.Id = menu.CategoryId;
                AR.Data = RenderPartialViewToString("_MenuList", menus);

                AR.SetSuccess("已成功新增菜单");
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            AR.Setfailure("编辑菜单失败");
            return Json(AR, JsonRequestBehavior.DenyGet);

            //   return RedirectToAction("Index");

        }


        [HttpGet]
        [AllowAnonymous]
        public ActionResult EditMenu(int id)
        {          
            Menu vMenu = _menuService.GetById(id);
            MenuIM dto = _mapper.Map<MenuIM>(vMenu);
            return PartialView("_MenuEdit", dto);         
         
        }




        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<JsonResult> EditMenu(MenuIM menu)
        {

            if (ModelState.IsValid)
            {
                Menu vMenu = _mapper.Map<Menu>(menu);

                Menu orgMenu = _menuService.GetById(vMenu.Id);
                orgMenu.Title = vMenu.Title;
                orgMenu.MenuType = vMenu.MenuType;
                orgMenu.Active = vMenu.Active;
                orgMenu.Action = vMenu.Action;
                orgMenu.Area = vMenu.Area;
                orgMenu.CategoryId = vMenu.CategoryId;
                orgMenu.Controller = vMenu.Controller;
                orgMenu.Iconfont = vMenu.Iconfont;
                orgMenu.ParentId = vMenu.ParentId;
                orgMenu.Url = vMenu.Url;

                 _menuService.Update(orgMenu);
             
               // _menuService.ResetSort(orgMenu.CategoryId);

                var menus = await _menuService.GetMenus(vMenu.CategoryId);
                AR.Id = vMenu.CategoryId;
                AR.Data = RenderPartialViewToString("_MenuList", menus);

                AR.SetSuccess("已成功保存菜单");
                return Json(AR, JsonRequestBehavior.DenyGet);

            }

            AR.Setfailure("编辑菜单失败");
            return Json(AR, JsonRequestBehavior.DenyGet);



        }



        // POST: Admin/User/Delete
        [HttpPost]    
        [ValidateAntiForgeryToken]
        public ActionResult Delete(int id)
        {

            Menu vMenu = _menuService.GetMenuWithChildMenus(id);
           
            if (vMenu != null)
            {

                int cid = vMenu.CategoryId;
                if(SettingsManager.Menu.BackMenuCId == cid)
                {
                    if(User.UserId.ToString() != SettingsManager.User.Founder)
                    {
                        AR.SetWarning(string.Format(Messages.NotFounderCanNotDelete,EntityNames.Menu));
                        return Json(AR, JsonRequestBehavior.DenyGet);
                    }

                }

                if (vMenu.ChildMenus.Any())
                {
                    AR.Setfailure(string.Format(Messages.AlertDeleteFailureHasChild, EntityNames.Menu));
                    return Json(AR, JsonRequestBehavior.DenyGet);
                }

               
                vMenu.Roles.Clear();
                _menuService.Delete(vMenu);
                //var menus = await _menuService.GetMenus(cid);
                //return PartialView("_MenuList", menus);
                AR.SetSuccess(string.Format(Messages.AlertDeleteSuccess,EntityNames.Menu));
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
            AR.Setfailure(string.Format(Messages.AlertDeleteFailure,EntityNames.Menu));
            return Json(AR, JsonRequestBehavior.DenyGet);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> UpDownMove(int id, bool isUp, int categoryId)
        {

            if (isUp)
            {
                var result = _menuService.UpMoveMenu(id);

                if (result == 0)
                {
                    AR.SetInfo("已经在第一位！");
                    return Json(AR, JsonRequestBehavior.DenyGet);
                }
            }
            else
            {
                var result = _menuService.DownMoveMenu(id);

                if (result == 0)
                {
                    AR.SetInfo("已经在末位！");
                    return Json(AR, JsonRequestBehavior.DenyGet);
                }

            }

            var menus = await _menuService.GetMenus(categoryId);
            AR.Id = categoryId;
            AR.Data = RenderPartialViewToString("_MenuList", menus);

            AR.SetSuccess("菜单排位成功！");
            return Json(AR, JsonRequestBehavior.DenyGet);

            //AR.Setfailure("菜单排位失败！");
            //return Json(AR, JsonRequestBehavior.DenyGet);

        }


        [HttpPost]
        public JsonResult IsExpand(int id)
        {
            var menu = _menuService.GetById(id);
            if (menu != null)
            {
                menu.IsExpand = !menu.IsExpand;
                _menuService.Update(menu);

                AR.SetSuccess(Messages.AlertActionSuccess);
                return Json(AR, JsonRequestBehavior.DenyGet);

            }
            AR.Setfailure(Messages.AlertActionFailure);
            return Json(AR, JsonRequestBehavior.DenyGet);

        }

        [HttpPost]
        public JsonResult IsActive(int id)
        {
            var menu = _menuService.GetById(id);
            if (menu != null)
            {
                menu.Active = !menu.Active;
                _menuService.Update(menu);                

                AR.SetSuccess(Messages.AlertActionSuccess);
                return Json(AR, JsonRequestBehavior.DenyGet);

            }
            AR.Setfailure(Messages.AlertActionFailure);
            return Json(AR, JsonRequestBehavior.DenyGet);

        }

        [HttpPost]
        public async Task<JsonResult> ResetSort(int id)
        {
            try
            {
                _menuService.ResetSort(id);

                var menus = await _menuService.GetMenus(id);
                AR.Id = id;
                AR.Data = RenderPartialViewToString("_MenuList", menus);

                AR.SetSuccess(Messages.AlertActionSuccess);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
            catch (Exception er)
            {
                AR.Setfailure(er.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }


        }


        [HttpGet]
        // GET: Roles/Create
        public ActionResult MoveMenu(int id)
        {
            var menu = _menuService.GetById(id);
            var menus = _menuService.GetMenusByCategoryId(menu.CategoryId);
            MoveMenuVM vm = new MoveMenuVM
            {
                Id = id,
                Menus = _mapper.Map<List<Menu>, List<MenuVM>>(menus),
                CurrentParentId = (int)menu.ParentId,
                CategoryId = menu.CategoryId
            };

            return PartialView("_MoveMenu", vm);
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> MoveMenu(int Id, int menuId)
        {

            if (Id > 0)
            {
                var menu = _menuService.GetById(Id);
                menu.ParentId = menuId;
                _menuService.Update(menu);

                _menuService.ResetSort(menu.CategoryId);

                var menus = await _menuService.GetMenus(menu.CategoryId);
                AR.Id = menu.CategoryId;
                AR.Data = RenderPartialViewToString("_MenuList", menus);
             
                return Json(AR, JsonRequestBehavior.DenyGet);

            }
            AR.Setfailure("移动菜单失败");
            return Json(AR, JsonRequestBehavior.DenyGet);
        }


    }
}
